<template>
  <el-cascader 
    v-model="selectedValue" 
    placeholder="请选择班级" 
    size="small" 
    :props="cascaderProps" 
    @change="handleChange"
    filterable 
    clearable
  />
</template>

<script>
import api from '@/common/api'

export default {
  name: 'ClassSelect',
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectedValue: this.normalize(this.value),
      cascaderProps: {
        checkStrictly: true,
        lazy: true,
        lazyLoad: this.lazyLoad
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        this.selectedValue = this.normalize(val)
      },
      immediate: true
    }
  },
  methods: {
    normalize(val) {
      if (!Array.isArray(val)) return []
      return val.map(v => v != null ? String(v) : v)
    },
    async lazyLoad(node, resolve) {
      const { level, value } = node
      if (level >= 3) {
        resolve([])
        return
      }

      const params = {}
      let method = api.admin_getSchoolList
      if (level === 1) {
        method = api.admin_getGradeList
        params.schoolId = value
      } else if (level === 2) {
        method = api.admin_getClassList
        params.gradeId = value
      }

      try {
        const res = await method(params)
        resolve(res.data.data.map(item => ({
          value: String(item.id),
          label: item.name,
          leaf: level === 2,
          children: []
        })))
      } catch (error) {
        console.error('加载数据失败:', error)
        resolve([])
      }
    },
    handleChange(val) {
      this.$emit('input', val)
      this.$emit('change', val)
    }
  }
}
</script> 
